package unrn.isiii.bean;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import unrn.isiii.dao.EnvaseDao;
import unrn.isiii.dao.TaskDao;
import unrn.isiii.model.Envase;
import unrn.isiii.model.Task;

@Component("envaseController")
public class EnvaseController {

	private static final Logger logger = LoggerFactory
			.getLogger(ClienteController.class);

	private Envase envase = new Envase();
	private List<Envase> envases;

	@Autowired
	private EnvaseDao envaseDao;

	public String getMessage() {
		logger.debug("Returning message from task home bean");
		return "Hello from Spring";
	}

	public Envase getEnvase() {
		return envase;
	}

	public EnvaseDao getEnvaseDao() {
		return envaseDao;
	}

	public void setClienteDao(EnvaseDao envaseDao) {
		this.envaseDao = envaseDao;
	}

	public void setEnvase(Envase envase) {
		this.envase = envase;
	}

	public void setEnvases(List<Envase> envases) {
		this.envases = envases;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void saveEnvase() {
		if (envase.getId() == null)
			envaseDao.create(envase);
		else
			envaseDao.update(envase);
		envase = new Envase();
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Alta",
				"realizada con exito.");
		if (FacesContext.getCurrentInstance() != null)
			FacesContext.getCurrentInstance().addMessage(null, msg);
		invalidateTasks();
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void eliminar(Long id) {
		envaseDao.delete(id);
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Alta",
				"realizada con exito.");
		if (FacesContext.getCurrentInstance() != null)
			FacesContext.getCurrentInstance().addMessage(null, msg);
		invalidateTasks();
	}

	private void invalidateTasks() {
		envases = null;
	}

	public List<Envase> getEnvases() {
		if (envases == null) {
			envases = envaseDao.findAll();
		}
		return envases;
	}

	public void seleccionarEnvase(Envase envase) {
		setEnvase(envase);
	}
}
